from sqlmodel import select, desc
from fastapi import Depends
import typing as T
import json
from ...init.Global import Session
from ...pojo import UserChatHistory, UserChatHistoryVO


class _UserHistoryMapper:
    session: Session = None

    def __call__(self, session: Session):
        self.session = session
        return self

    async def getChatHistory(self, sessionId: int, count: int):
        result = (
            (
                await self.session.execute(
                    select(UserChatHistory)
                    .where(UserChatHistory.sessionId == sessionId)
                    .order_by(desc(UserChatHistory.id))
                    .limit(count)
                )
            )
            .scalars()
            .all()
            if count != -1
            else (
                (
                    await self.session.execute(
                        select(UserChatHistory)
                        .where(UserChatHistory.sessionId == sessionId)
                        .order_by(desc(UserChatHistory.id))
                    )
                )
                .scalars()
                .all()
            )
        )
        return [
            UserChatHistoryVO(
                id=item.id,
                isAi=item.isAi,
                sessionId=item.sessionId,
                content=json.loads(item.content),
            )
            for item in result
        ]


UserHistoryMapper = T.Annotated[_UserHistoryMapper, Depends(_UserHistoryMapper())]
